/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mrs.models;

import java.util.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import mrs.database.*;

/**
 *
 * @author pablo
 */
public class Ingredient {

  public String name;
  public String origin;
  public String group;
  public float energyKcal100g;
  
  public Ingredient(String name) {
    this.name = name;
  }
  
  public Ingredient(String name,
                    String origin,
                    String group,
                    int energyKcal100g) {
    this.name = name;
    this.origin = origin;
    this.group = group;
    this.energyKcal100g = energyKcal100g;
  }
  
  @Override
  public boolean equals(Object aThat) {
    
    if ( this == aThat ) return true;
    if ( !(aThat instanceof Ingredient) ) return false;
    Ingredient that = (Ingredient)aThat;
    return (this.name.equals(that.name));
    
  }

  @Override
  public int hashCode() {
    int hash = 7;
    hash = 37 * hash + (this.name != null ? this.name.hashCode() : 0);
    return hash;
  }

  @Override
  public String toString() {
    return this.name;
  }
  
  public static ArrayList<Ingredient> getAll() throws Exception {
    try {

      ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
      Ingredient ingredient;

      Statement stat = DB.connect().createStatement();
      ResultSet rs = stat.executeQuery("select * from Ingredient;");

      while (rs.next()) {
        ingredient = new Ingredient(rs.getString("name"),
                                    rs.getString("origin"),
                                    rs.getString("group"),
                                    rs.getInt("energy_kcal_100g"));
        ingredients.add(ingredient);
        System.out.println(ingredient);
      }
      
      rs.close();
      DB.disconnect();
      
      return ingredients;
      
    } catch (SQLException ex) {
      Logger.getLogger(Ingredient.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    }
  }
}
